package com.example.receiptmanage.controller;

import com.example.receiptmanage.dto.ReceiptInfoDTO;
import com.example.receiptmanage.dto.WeeklyExpenseDTO;
import com.example.receiptmanage.entity.Receipts;
import com.example.receiptmanage.entity.User;
import com.example.receiptmanage.service.ReceiptService;
import com.example.receiptmanage.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.receiptmanage.util.JwtUtil;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PutMapping;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/receipts")
public class ReceiptController {
    
    @Autowired
    private ReceiptService receiptService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserService userService;
    
    @GetMapping("/recent")
    public ResponseEntity<?> getRecentReceipts(@AuthenticationPrincipal UserDetails userDetails) {
        if (userDetails == null) {
            return ResponseEntity.status(401).body("未认证");
        }
        
        Optional<User> optionalUser = userService.findByUsername(userDetails.getUsername());
        if (optionalUser.isEmpty()) {
            return ResponseEntity.status(404).body("用户不存在");
        }
        
        User user = optionalUser.get();
        List<ReceiptInfoDTO> receiptInfoDTO = receiptService.getRecentReceiptsByUserId(user.getUserId());
        return ResponseEntity.ok(receiptInfoDTO);
    }

    @GetMapping("/weekly-expenses")
    public ResponseEntity<List<WeeklyExpenseDTO>> getWeeklyExpenses(
            @RequestHeader("Authorization") String token) {
        try {
            
            // 检查token格式
            if (!token.startsWith("Bearer ")) {
                return ResponseEntity.status(401).body(null);
            }
            
            // 提取并清理token
            String cleanToken = token.substring(7).trim(); // 使用substring替代replace
            System.out.println("Cleaned token: " + cleanToken);
            
            // 验证token格式
            if (cleanToken.split("\\.").length != 3) {
                return ResponseEntity.status(401).body(null);
            }
            
            String username = jwtUtil.extractUsername(cleanToken);
            Optional<User> optionalUser = userService.findByUsername(username);
            if (optionalUser.isEmpty()) {
                return ResponseEntity.status(404).build();
            }
            
            Long userId = optionalUser.get().getUserId();
            List<WeeklyExpenseDTO> expenses = receiptService.getWeeklyExpenses(userId);
            return ResponseEntity.ok(expenses);
        } catch (Exception e) {
            System.err.println("Token processing error: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(401).body(null);
        }
    }

    // 获取单个票据详情
    @GetMapping("/{receiptId}")
    public ResponseEntity<?> getReceiptById(
            @PathVariable Long receiptId,
            @AuthenticationPrincipal UserDetails userDetails
    ) {
        if (userDetails == null) {
            return ResponseEntity.status(401).body("未认证");
        }
        
        Optional<User> optionalUser = userService.findByUsername(userDetails.getUsername());
        if (optionalUser.isEmpty()) {
            return ResponseEntity.status(404).body("用户不存在");
        }
        
        User user = optionalUser.get();
        Optional<Receipts> receipt = receiptService.getReceiptByIdAndUserId(receiptId, user.getUserId());
        
        if (receipt.isEmpty()) {
            return ResponseEntity.status(404).body("票据不存在");
        }
        
        return ResponseEntity.ok(receipt.get());
    }
    
    // 更新票据信息
    @PutMapping("/update")
    public ResponseEntity<?> updateReceipt(
            @PathVariable Long receiptId,
            @RequestBody Receipts updatedReceipt,
            @AuthenticationPrincipal UserDetails userDetails
    ) {
        if (userDetails == null) {
            return ResponseEntity.status(401).body("未认证");
        }
        
        Optional<User> optionalUser = userService.findByUsername(userDetails.getUsername());
        if (optionalUser.isEmpty()) {
            return ResponseEntity.status(404).body("用户不存在");
        }
        
        User user = optionalUser.get();
        
        // 确保票据属于当前用户
        Optional<Receipts> existingReceipt = receiptService.getReceiptByIdAndUserId(receiptId, user.getUserId());
        if (existingReceipt.isEmpty()) {
            return ResponseEntity.status(404).body("票据不存在");
        }
        
        // 更新票据信息
        updatedReceipt.setReceiptId(receiptId);
        updatedReceipt.setUserId(user.getUserId());
        Receipts savedReceipt = receiptService.updateReceipt(updatedReceipt);
        
        return ResponseEntity.ok(savedReceipt);
    }

}